﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using Telerik.Windows.Documents.Fixed.Model.Editing;

namespace Com.Lancetinc.Evs.Reports.RadPdf;

internal class PdfRenderer
{
    private readonly List<UIElementRendererBase> _renderers = new();

    internal void AddRenderer(UIElementRendererBase renderer)
    {
        _renderers.Add(renderer);
    }

    internal void Render(FrameworkElement element, FixedContentEditor drawingSurface)
    {
        var context = new PdfRenderContext(drawingSurface, this);
        Render(element, context, true);
    }

    internal void Render(FrameworkElement element, PdfRenderContext context, bool isRoot)
    {
        if (element == null || element.Visibility != Visibility.Visible || element.Opacity == 0)
        {
            return;
        }

        using var compositeSave = new CompositeDisposableObject();
        compositeSave.Add(UIElementRendererBase.SaveMatrixPosition(context.drawingSurface, element, isRoot));
        compositeSave.Add(UIElementRendererBase.SaveClip(context.drawingSurface, element));
        compositeSave.Add(UIElementRendererBase.SaveOpacity(context, context.opacity * element.Opacity));

        foreach (var renderer in _renderers)
        {
            var success = renderer.Render(element, context);
            if (success)
            {
                return;
            }
        }

        Debug.WriteLine("" + element + " could not be exported correctly.");
    }
}